import { t } from 'i18next'
import { fetchGetAllVRSFile, fetchGetAllVRSFolders } from '@/api/manager/playVideo'
import { FetchPlayVideoFile, FetchPlayVideoFolder, ParamsProps } from '@/api/manager/playVideo/interface'
import { Modal, Search, Tree, ColumnProps, FlattenNode, TreeNodeData } from '@kedacom/react-next'
import Table from '@/components/Table'
import dayjs from '@/plugins/dayjs'
import { useEffect, useState } from 'react'
import { usePlayVideoStore } from '../store'
import { FileDialogWrap } from './style'

/**会议放像文件选择 */
interface FileWrapProps {
	/**控制弹框展示 */
	isOpen: boolean
	/**弹框确定按钮回调 */
	onOk: Function
	/**弹框取消按钮回调 */
	onIconClose: () => void
}
interface FolderProps extends TreeNodeData<'id', 'name'> {}
interface ParamsFilterProps {
	id: string
	pageIndex: number
	pageSize: number
	key: string
}
/**
 * 会议放像文件选择弹窗
 * @param param0
 * @returns
 */
const FileWrap = ({ isOpen, onIconClose, onOk }: FileWrapProps) => {
	/**放像文件夹数据 */
	const [treeData, setTreeData] = useState<FolderProps[]>([])
	/**放像文件列表数据 */
	const [tableData, setTableData] = useState<FetchPlayVideoFile[]>([])
	/**放像文件列表总数 */
	const [total, setTotal] = useState<number>(0)
	const [row, setRow] = useState<FetchPlayVideoFile | null>(null)
	const { setSelectVideoFile } = usePlayVideoStore((state) => ({
		setSelectVideoFile: state.setSelectVideoFile,
	}))
	/**放像文件表格列 */
	const columns: ColumnProps<FetchPlayVideoFile>[] = [
		{
			title: t('名称'),
			dataKey: 'name',
			width: 160,
			render: (rowData, value, index) => {
				return <span title={value}>{value}</span>
			},
		},
		{
			title: t('时长'),
			width: 60,
			dataKey: 'duration',
			render: (rowData, value, index) => {
				let day = dayjs().format('YYYY-MM-DD')
				let time =
					dayjs(new Date(day + ' 00:00:00').getTime() + parseInt(value) * 1000).format('HH:mm:ss') || ''
				return <span title={time}>{time}</span>
			},
		},
		{
			title: t('创建时间'),
			dataKey: 'create_time',
			render: (rowData, value, index) => {
				let time = dayjs(value).format('YYYY-MM-DD HH:mm:ss') || ''
				return <span title={time}>{time}</span>
			},
		},
	]
	const [params, setParams] = useState<ParamsFilterProps>({
		id: '',
		pageIndex: 1,
		pageSize: 20,
		key: '',
	})
	/**获取放像文件列表 */
	const getVRSFile = (id: string, filter: ParamsProps) => {
		fetchGetAllVRSFile(id, filter).then((res) => {
			setTotal(res?.total ?? 0)
			setTableData(res?.list ?? [])
		})
	}
	/**放像文件夹节点点击回调函数 */
	const treeClick = (e: any, Key: any, node: FlattenNode) => {
		if (Key !== params.id) {
			setParams({
				...params,
				id: Key,
				pageIndex: 1,
				key: '',
			})
		}
	}
	/**放像文件夹节数据处理，扁平化转树状 */
	const flatToTree = (parentId: string, list: FetchPlayVideoFolder[]) => {
		let treeData: FolderProps[] = []
		list.map((item) => {
			let name = item.name === 'ALL' ? t('全部') : item.name === 'UnGroup' ? t('未分组') : item.name
			let _item: FolderProps = { ...item, children: [], isLeaf: false, name: name }
			//parentId === '0' && !item.parent_id 这个判断是兼容vrs切换成local模式，数据结构不存在parent_id
			if (item.parent_id === parentId || (parentId === '0' && !item.parent_id)) {
				treeData.push(_item)
				let _list: FolderProps[] = flatToTree(item.id, list)
				_item.children = _list
				_item.isLeaf = _list.length <= 0
			}
			return item
		})
		return treeData
	}
	/**文件列表搜索条件变化时，重新获取文件列表 */
	const onchange = (name: string, value: any) => {
		let _params = { ...params, [name]: value }
		setParams(_params)
	}
	const onSearch = (name: string, value: any) => {
		let _params = { ...params, [name]: value, pageIndex: 1 }
		setParams(_params)
	}
	/**选中文件列表某行数据 */
	const onRowClick = (row: FetchPlayVideoFile) => {
		setRow(row)
	}
	useEffect(() => {
		if (isOpen) {
			/**弹出框弹出时，获取文件夹数据 */
			fetchGetAllVRSFolders().then((res) => {
				let list = flatToTree('0', res?.list ?? [])
				setTreeData(list)
			})
		}
	}, [isOpen])
	useEffect(() => {
		if (params.id) {
			getVRSFile(params.id, { start: (params.pageIndex - 1) * params.pageSize, key: params.key })
		}
	}, [params])
	const onClickOk = () => {
		row && setSelectVideoFile(row)
		onOk && onOk()
	}
	return (
		<Modal
			open={isOpen}
			title={t('会议放像文件选择')}
			width={720}
			height={500}
			okText={t('选择')}
			onCancel={onIconClose}
			onOk={() => onClickOk()}
			cancelText={t('取消')}
		>
			<FileDialogWrap>
				<div className="file-left">
					<div className="header">
						<span className="title">{t('文件夹列表')}</span>
					</div>
					<Tree
						className="context"
						treeData={treeData ?? []}
						valueField="id"
						labelField="name"
						virtualized
						height={310}
						onClick={treeClick}
						defaultExpandAll
						selectedKeys={[params.id]}
					/>
				</div>
				<div className="file-right">
					<div className="header">
						<span className="title">{t('文件列表')}</span>
						<Search
							value={params.key}
							width={110}
							placeholder={t('请输入搜索内容')}
							onChange={(e, v) => {
								onSearch('key', v)
							}}
							onSearch={(e, value) => onSearch('key', value)}
						></Search>
					</div>
					<div className="context">
						<Table
							rowIdField="id"
							minHight={'auto'}
							showSelectColumn={false}
							columns={columns}
							pager={{ page: params.pageIndex, size: params.pageSize, total: total }}
							nodata={t('暂无数据')}
							onPageChange={(pageIndex) => onchange('pageIndex', pageIndex ?? 1)}
							tableDataList={tableData}
							onRowClick={(e, rowData, id: string, nextSelected) => onRowClick(rowData)}
							i18n={{ order: t('序号') }}
						/>
					</div>
				</div>
			</FileDialogWrap>
		</Modal>
	)
}
export default FileWrap
